<script setup>
import {
    Edit,
    Delete,
    Search,
    Plus,
    Check,
    Close,
    View
} from '@element-plus/icons-vue'
import { ref } from 'vue'
import { formatDate } from '@/utils/format.js'
const categorys = ref([])
const visibleDrawer = ref(false)
const title = ref('')
const categoryModel = ref({
    categoryName: '',
    description: ''
})

import { getCategoryListService, addCategoryService, editCategoryService, deleteCategoryService } from '@/api/category.js'
import { ElMessage } from 'element-plus'
// 查询分类
const getCategoryList = async () => {
    const res = await getCategoryListService()
    categorys.value = res.data
}
getCategoryList()
// 清空表单
const clearForm = () => {
    categoryModel.value = {
        categoryName: '',
        description: ''
    }
}
//校验
const rules = ref({
    categoryName: [
        { required: true, message: '分类名称不能为空', trigger: 'blur' },
        { min: 2, max: 10, message: '分类名称长度在2-10个字符之间', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '分类描述不能为空', trigger: 'blur' },
        { min: 2, max: 300, message: '分类描述长度在2-300个字符之间', trigger: 'blur' }
    ]
})
const categoryForm = ref(null)
// 添加分类
const addCategory = async () => {
    await categoryForm.value.validate(async (valid) => {
        if (!valid) {
            return
        }
        console.log(categoryModel.value);
        const res = await addCategoryService(categoryModel.value)
        ElMessage.success(res.msg ? res.msg : '添加成功')
        getCategoryList()
        visibleDrawer.value = false
    })
}

// 回显分类
const editCategory = (row) => {
    // 使用深拷贝
    categoryModel.value = JSON.parse(JSON.stringify(row))
    visibleDrawer.value = true
    title.value = '编辑分类'
}

// 编辑分类
const updateCategory = async () => {
    const res = await editCategoryService(categoryModel.value)
    ElMessage.success(res.msg ? res.msg : '编辑成功')
    getCategoryList()
    visibleDrawer.value = false

}
// 删除分类
import { ElMessageBox } from 'element-plus'
const deleteCategory = async (row) => {
    ElMessageBox.confirm(
        '你确定要删除该分类信息么?',
        '温馨提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            draggable: true,
        }
    )
        .then(async () => {
            let res = await deleteCategoryService(row.id)
            if (res.code == 0) {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                getCategoryList()
                return
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除',
            })
        })
}

// 弹框
const viewVisible = ref(false)
const viewContent = ref('')
const categoryTitle = ref('')
const showInfo = (row) => {
    categoryTitle.value = row.categoryName
    viewContent.value = row.description
    viewVisible.value = true
}

// 富文本编辑器
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, shallowRef } from "vue";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useTokenStore } from '@/stores/token.js'


const tokenStore = useTokenStore()
/* wangEditor5 初始化开始 */
const editorRef = shallowRef()  // 编辑器实例，必须用 shallowRef
const mode = 'default'
const editorConfig = { MENU_CONF: {} }
// 图片上传配置
editorConfig.MENU_CONF['uploadImage'] = {
    headers: {
        'Authorization': tokenStore.token,
    },
    server: '/api/wang/upload',  // 服务端图片上传接口
    fieldName: 'file'  // 服务端图片上传接口参数
}
// 组件销毁时，也及时销毁编辑器，否则可能会造成内存泄漏
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})
// 记录 editor 实例，重要！
const handleCreated = (editor) => {
    editorRef.value = editor
}
/* wangEditor5 初始化结束 */

</script>
<template>
    <div class="page-container">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span class="title">商品分类管理</span>
                    <div class="header-actions">
                        <el-button type="primary" @click="visibleDrawer = true, title = '添加分类', clearForm()" class="add-button">
                            <el-icon><Plus /></el-icon>添加分类
                        </el-button>
                    </div>
                </div>
            </template>
            
            <el-table 
                :data="categorys" 
                style="width: 100%" 
                border 
                stripe
                :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
                :row-style="{ height: '60px' }"
                :cell-style="{ padding: '8px 0' }"
                highlight-current-row>
                <el-table-column label="序号" width="80" type="index" align="center" />
                <el-table-column label="分类名称" prop="categoryName" min-width="150" align="center" />
                <el-table-column label="详细描述" min-width="220" align="center">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="showInfo(row)" class="view-button">
                            <el-icon><View /></el-icon>查看详情
                        </el-button>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="更新时间" prop="updateTime" width="180" align="center" /> -->
                <el-table-column prop="updateTime" label="操作时间" min-width="180" align="center" >
                    <template #default="{ row }">
                        {{ formatDate(row.updateTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" align="center" fixed="right">
                    <template #default="{ row }">
                        <div class="operation-buttons">
                            <el-tooltip content="编辑" placement="top">
                                <el-button type="primary" circle @click="editCategory(row)" size="small">
                                    <el-icon><Edit /></el-icon>
                                </el-button>
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top">
                                <el-button type="danger" circle @click="deleteCategory(row)" size="small">
                                    <el-icon><Delete /></el-icon>
                                </el-button>
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
                <template #empty>
                    <el-empty description="暂无分类数据" />
                </template>
            </el-table>
        </el-card>

        <!-- 详情弹框 -->
        <el-dialog 
            v-model="viewVisible" 
            width="60%" 
            destroy-on-close
            class="custom-dialog"
            :show-close="false">
            <template #header>
                <div class="dialog-header">
                    <div class="dialog-title">
                        <el-icon class="title-icon"><Search /></el-icon>
                        <span>{{ categoryTitle }}</span>
                    </div>
                    <el-button class="close-button" @click="viewVisible = false" circle>
                        <el-icon><Close /></el-icon>
                    </el-button>
                </div>
            </template>
            <div class="dialog-content-wrapper">
                <div class="dialog-content" v-html="viewContent"></div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="viewVisible = false" class="close-dialog-button">
                        <el-icon><Close /></el-icon>关闭
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 添加/编辑分类抽屉 -->
        <el-drawer 
            v-model="visibleDrawer" 
            :title="title" 
            direction="rtl" 
            size="60%"
            destroy-on-close
            :show-close="false"
            class="custom-drawer">
            <template #header>
                <div class="drawer-header">
                    <div class="drawer-title">
                        <el-icon class="title-icon"><component :is="title === '添加分类' ? Plus : Edit" /></el-icon>
                        <span>{{ title }}</span>
                    </div>
                    <el-button class="close-button" @click="visibleDrawer = false" circle>
                        <el-icon><Close /></el-icon>
                    </el-button>
                </div>
            </template>
            <div class="drawer-content">
                <el-form 
                    :model="categoryModel" 
                    label-width="100px" 
                    ref="categoryForm" 
                    :rules="rules"
                    class="drawer-form">
                    <el-form-item label="分类名称" prop="categoryName">
                        <el-input v-model="categoryModel.categoryName" placeholder="请输入分类名称" class="custom-input"></el-input>
                    </el-form-item>
                    <el-form-item label="详细描述" prop="description">
                        <div class="editor-container">
                            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :mode="mode" />
                            <Editor style="height: 500px; overflow-y: hidden;" v-model="categoryModel.description" :mode="mode"
                                :defaultConfig="editorConfig" @onCreated="handleCreated" />
                        </div>
                    </el-form-item>
                    <el-form-item class="drawer-footer">
                        <el-button type="primary" @click="title === '添加分类' ? addCategory(categoryForm) : updateCategory(categoryForm)" class="submit-button">
                            <el-icon><Check /></el-icon>{{ title === '添加分类' ? '创建' : '更新' }}
                        </el-button>
                        <el-button @click="visibleDrawer = false" class="cancel-button">
                            <el-icon><Close /></el-icon>取消
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-drawer>
    </div>
</template>

<style lang="scss" scoped>
.page-container {
    padding: 20px;
    
    .box-card {
        margin-bottom: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        transition: all 0.3s;

        &:hover {
            box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
        }
    }
    
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .title {
            font-size: 16px;
            font-weight: bold;
            color: #303133;
        }
        
        .header-actions {
            display: flex;
            gap: 10px;
        }
    }
}

.custom-input {
    width: 220px;
}

.view-button, .search-button, .reset-button {
    padding: 8px 16px;
    font-size: 14px;
    border-radius: 4px;
    display: inline-flex !important;
    align-items: center;
    gap: 5px;
    cursor: pointer;
    background-color: var(--el-color-primary) !important;
    border-color: var(--el-color-primary) !important;
    color: white !important;
    
    &:hover {
        background-color: var(--el-color-primary-light-3) !important;
        border-color: var(--el-color-primary-light-3) !important;
    }
    
    .el-icon {
        margin-right: 4px;
        font-size: 16px;
    }
}

.add-button, .submit-button {
    padding: 8px 16px;
    font-size: 14px;
    border-radius: 4px;
    display: inline-flex !important;
    align-items: center;
    gap: 5px;
    background-color: var(--el-color-primary) !important;
    border-color: var(--el-color-primary) !important;
    color: white !important;
    cursor: pointer;
    
    &:hover {
        background-color: var(--el-color-primary-light-3) !important;
        border-color: var(--el-color-primary-light-3) !important;
    }
    
    .el-icon {
        margin-right: 4px;
        font-size: 16px;
    }
}

.dialog-header, .drawer-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #e4e7ed;
    
    .dialog-title, .drawer-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 16px;
        font-weight: bold;
        
        .title-icon {
            font-size: 20px;
            color: var(--el-color-primary);
        }
    }
}

.dialog-content-wrapper {
    padding: 20px;
}

.dialog-content {
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.close-dialog-button, .cancel-button {
    padding: 8px 16px;
    font-size: 14px;
    border-radius: 4px;
    display: inline-flex !important;
    align-items: center;
    gap: 5px;
    cursor: pointer;
    
    .el-icon {
        margin-right: 4px;
        font-size: 16px;
    }
}

.operation-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
}

.drawer-content {
    padding: 20px;
    height: calc(100% - 120px);
    overflow-y: auto;
}

.drawer-form {
    padding: 20px;
}

.drawer-footer {
    margin-top: 40px;
    text-align: center;
}

:deep(.el-dialog__body) {
    padding: 20px;
}

:deep(.el-drawer__body) {
    padding: 0;
    position: relative;
    overflow: hidden;
}

.editor-container {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
}

.el-button {
    display: inline-flex;
    align-items: center;
    gap: 4px;
}
</style>